package com.karl.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.karl.entity.User;
import com.karl.service.UserManager;
import com.karl.vo.UserRegisterInfo;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Component("userP")
@Scope("prototype")
public class UserAction extends ActionSupport implements ModelDriven<UserRegisterInfo>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	List<User> users;
	User user;
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public List<User> getUsers() {
		return users;
	}
	public void setUsers(List<User> users) {
		this.users = users;
	}
	private UserManager userManager;
	private UserRegisterInfo info = new UserRegisterInfo();
	
	public UserManager getUserManager() {
		return userManager;
	}
	@Resource
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public void validate(){   
		if(!info.getPassword().equals(info.getPassword2()))
			this.addFieldError("registerError", "两次输入的密码不一致!");// 执行完这句之后直接返回 input  而且不执行 doReg
			
	}
	public String doReg(){
//		System.out.println("进来啦码1111");
		User user = new User();
	//	System.out.println(info.getUsername() + info.getPassword());
		user.setUsername(info.getUsername());
		user.setPassword(info.getPassword());
		
		if(info.getPassword().equals(info.getPassword2()) && !userManager.exists(user)){
			userManager.add(user);
			return SUCCESS;
		}else{
			this.addFieldError("registerError", "用户名已存在!");
			return "fail";
		}
	}

	
	
	//默认去执行execute
	@Override
	public String execute() throws Exception {
		
		User user = new User();
		System.out.println(info.getUsername() + info.getPassword());
		user.setUsername(info.getUsername());
		user.setPassword(info.getPassword());
		
		if(!userManager.exists(user)){
			userManager.add(user);
			return SUCCESS;
		}else{
			return "fail";
		}
								
	}
	@Override
	public UserRegisterInfo getModel() {
		// TODO Auto-generated method stub
		return info;
	}
	
	public String list(){
		this.users = userManager.getUsers();
		return "list";
	}
	public String load(){
		this.user = userManager.loadUserById(info.getId());
		return "load";
	}
	
	
	
}
